﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Configuration;
using System.Xml.Linq;
using System.Web.Mvc;
using MyAlbum.Model;
using MyAlbum.Data;
using MyAlbum.Logging;
using System.Threading;

using PersonalAlbum.Caching;
using MyAlbum.Services;
using System.Xml.Schema;
using System.Xml;
using System.Drawing;

namespace PersonalAlbum
{
    public class Utils
    {

        public static string FixLink(string original, Uri request)
        {
            if (!Uri.IsWellFormedUriString(original, UriKind.Absolute))
            {
                if (!original.StartsWith("~"))
                {
                    ///it's not root, make our link relative to root
                    if (request.PathAndQuery != "/")
                    {
                        original = "~/" + original.TrimStart('/');
                    }
                }
                else
                {
                    /*it seems that when no path is present in the url the image doesn't show*/
                    if (request.PathAndQuery == "/")
                    {
                        ///we're on root anyway
                        original = original.TrimStart('/', '~');
                    }
                }
            }
            return original;
        }


        //public static void ScaleThumbnail(Entry entry)
        //{
        //    if (GetValue OrDefault<bool>("Scale thumbnail", false))
        //    {
        //        if (entry.Width.HasValue && entry.Height.HasValue)
        //        {
        //            decimal curHeight = entry.Height.Value;
        //            decimal curWidth = entry.Width.Value;
        //            if (curHeight == 0 || curWidth == 0)
        //            {
        //                return;
        //            }
        //            decimal maxHeight = GetValueO rDefault<decimal>("Thumb height", 300);
        //            decimal maxWidth = GetValueO rDefault<decimal>("Thumb width", 300);
        //            if (maxHeight < curHeight || maxWidth < curWidth)
        //            {
        //                decimal scale;
        //                if (maxHeight < curHeight)
        //                {
        //                    scale = maxHeight / curHeight;
        //                }
        //                else
        //                {
        //                    scale = maxWidth / curWidth;
        //                }
        //                entry.Width = (int)(scale * curWidth);
        //                entry.Height = (int)(scale * curHeight);
        //            }
        //        }
        //    }
        //}

       



        public static string GetContent(string url)
        {
            string data = null;
            if (!string.IsNullOrEmpty(url))
            {

                if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
                {
                    WebClient wc = new WebClient();
                    data = wc.DownloadString(url);
                }
                else
                {
                    string path = HttpContext.Current.Server.MapPath(url);
                    if (File.Exists(path))
                    {
                        data = File.ReadAllText(path);
                    }
                }

            }
            return data;
        }

       

      
        public static string SaveFile(HttpPostedFileBase httpPostedFileBase)
        {
            string extension = Path.GetExtension(httpPostedFileBase.FileName);
            string fileName = Guid.NewGuid().ToString("N") + extension;
            string path = Path.Combine(HttpContext.Current.Server.MapPath(ConfigManager.ImagesPath), fileName);
            byte[] b = new byte[httpPostedFileBase.ContentLength];
            httpPostedFileBase.InputStream.Read(b, 0, b.Length);
            File.WriteAllBytes(path, b);
            return fileName;
        }

        public static string SaveFile(HttpPostedFileBase httpPostedFileBase, out int width, out int height)
        {
            string fileName = SaveFile(httpPostedFileBase);
            Bitmap bmp = new Bitmap(httpPostedFileBase.InputStream);
            width = bmp.Width;
            height = bmp.Height;
            return fileName;
        }

        public static void DeleteImage(string fileName)
        {
            if (fileName != null)
            {
                string path = Path.Combine(HttpContext.Current.Server.MapPath(ConfigManager.ImagesPath), fileName);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }

        

        internal static void DeleteErrorsFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }

        internal static Dictionary<string, string> LoadFilesFromDirectory(string path)
        {
            Dictionary<string, string> files = new Dictionary<string, string>();
            DirectoryInfo di = new DirectoryInfo(path);
            foreach (var item in di.GetFiles())
            {
                try
                {
                    files.Add(item.Name, File.ReadAllText(item.FullName));
                }
                catch (Exception e1)
                {
                    WebLogger.LogError(e1, "error reading from file " + item);
                }
            }
            return files;
        }

        internal static JsonResult JavascriptError(string message)
        {
            return new JsonResult() { Data = new { error = "true", message = message } };
        }
    }
}
